﻿#include "IM_VirtualData.h"

#include "jsoncpp/json.h"
#include "IM_Account.h"



IM_VirtualData::~IM_VirtualData()
{

}

IM_VirtualData::IM_VirtualData()
	:IM_DataInterface()
{

}

bool IM_VirtualData::init_data()
{
	Json::Reader read;
	Json::Value  root;
	std::string doc;
	
	std::ifstream in;
	in.open("data.json", std::ios_base::out);
	if (!in.is_open())
	{
		return false;
	}
	
	std::string s;
	while (getline(in,s))
	{
		m_json_stream += s;
	}
	
	
	return true;
}


bool IM_VirtualData::getFriendVector(const std::string & number, std::vector<std::string > &friends_vec)
{
	Json::Reader read;
	Json::Value  root;
	if (!read.parse(m_json_stream, root))
	{
		return false;
	}

	Json::Value friend_map = root["friend_map"];
	if (friend_map.isObject())
	{
		Json::Value friends = friend_map[number.c_str()];
		if (friends.isArray())
		{
			for (auto v:friends)
			{
				friends_vec.push_back(std::move(v.asString()));
			}
		}
		else
		{
			DEBUG("json : frends 不是一个数组 \n");
			return false;
		}
	}
	else
	{
		DEBUG("json ： friend_map  不是一个obj");
		return false;
	}

	return true;
}

bool IM_VirtualData::load_ac_all(std::map<std::string, IM_Account *> & ac_map)
{
	Json::Reader read;
	Json::Value  root;
	if (!read.parse(m_json_stream,root))
	{
		return false;
	}

	Json::Value ac_number = root["ac_numbers"];
	if (ac_number.isObject())
	{
		for (auto v:ac_number)
		{
			if (v.isObject())
			{
				std::string  num = v["number"].asString();
				std::string  name = v["name"].asString();
				char		 sex = (char)(v["sex"].asInt());
				std::string  emil = v["emil"].asString();
				IM_Account *a = new IM_Account(std::string(num), std::move(name), std::move(emil), sex,this);
				ac_map.emplace(std::move(num), a);
			}
			else
			{
				DEBUG("json : ac  不是一个object \n");
				return false;
			}
		}
	}
	else
	{
		DEBUG("json : ac_number 不是一个obj");
		return false;
	}

	return true;
}
